﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using Microsoft.Activities.UnitTesting.Persistence;
using MvcFlow.DefinitionProviders;
using MvcFlow.Hosts;
using MvcFlow.InstanceProviders;
using MvcFlow.Runtimes;
using MvcFlow.StateStores;

namespace MvcFlow.Samples.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

        public static void RegisterDependencyResolver()
        {
            var builder = new ContainerBuilder();
            var configuration = CreateWebApiConfiguration();

            builder.ConfigureWebApi(configuration);

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();
            builder.RegisterFilterProvider();
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModule(new AutofacWebTypesModule());

            RegisterDependencies(builder);

            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);
            configuration.ServiceResolver.SetResolver(resolver);
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        public static HttpConfiguration CreateWebApiConfiguration()
        {
            var configuration = GlobalConfiguration.Configuration;

            return configuration;
        }

        public static void RegisterDependencies(ContainerBuilder builder)
        {
            builder.Register(c => new HttpApplicationWorkflowHost()).As<IWorkflowHost>();
            builder.Register(c => new CookieWorkflowStateStore(c.Resolve<IWorkflowHost>())).As<IWorkflowStateStore>();
            builder.Register(c => new FileWorkflowDefinitionProvider()).As<IWorkflowDefinitionProvider>();
            builder.Register(c => new DynamicWorkflowInstanceProvider(c.Resolve<IWorkflowHost>(),c.Resolve<IWorkflowDefinitionProvider>())).As<IWorkflowInstanceProvider>().SingleInstance();
            builder.Register(c => new AsyncWorkflowRuntime(c.Resolve<IWorkflowStateStore>(), c.Resolve<IWorkflowInstanceProvider>(), c.Resolve<IWorkflowHost>(), new MemoryStore())).As<IWorkflowRuntime>().SingleInstance();
        }

        protected void Application_Start()
        {
            RegisterDependencyResolver();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            AreaRegistration.RegisterAllAreas();
            BundleTable.Bundles.RegisterTemplateBundles();
        }
    }
}